package com.atguigui.leetcode;

/**
 * 687.最长同值路径
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by WJX on 2022/9/2 15:50
 */
public class P687LongestUnivaluePath {
    public static void main(String[] args) {
        Solution solution = new P687LongestUnivaluePath().new Solution();
        // TO TEST
    }

    class Solution {
        int res;

        public int longestUnivaluePath(TreeNode root) {

            res = 0;
            dfs(root);
            return res;
        }

        private int dfs(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int left = dfs(root.left), right = dfs(root.right);
            int left1 = 0, right1 = 0;
            if (root.left != null && root.left.val == root.val) {
                left1 = left + 1;
            }
            if (root.right != null && root.right.val == root.val) {
                right1 = right + 1;
            }
            //将左节点和右节点相同路径的相加
            res = Math.max(res, left1 + right1);
            return Math.max(left1, right1);
        }


    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
